<script setup>
import { getKlineHistory } from '@/api/common/kline.js'
import Datafees from '@/config/kline/datafees.js'
import { getConfig, getIntervalList, getStudyList } from '@/config/kline/index.js'
import { _coinWebSocket } from '@/plugin/socket/index'
import { _t18, _klineTimeFormat } from '@/utils/public'
import { socketDict } from '@/config/dict'
import PubSub from 'pubsub-js'
import { _add, _div, _mul, priceFormat } from '@/utils/decimal'
import _ from 'lodash'
import { computed } from 'vue'
import { useMainStore } from '@/store'
import { useTradeStore } from '@/store/trade'
import { debounce, throttle } from 'lodash'
import { loadTradingViewScript, getTradingViewPathConfig, getTradingViewErrorMessage } from '@/utils/tradingview-loader'

const props = defineProps({
  /**
   * 类型
   * secondContract：秒合约
   * detail：详情
   */
  type: {
    type: String,
    default: 'detail'
  },

  /**
   * 商品信息
   */
  coinInfo: {
    type: Object,
    default: () => {}
  }
})
/**
 * 分辨率(k线图右侧刻度)
 */
const priceScale = computed(() => {
  let tempPricescale = 10000
  if (props.coinInfo?.amount > 100) {
    tempPricescale = 100
  } else if (props.coinInfo?.amount < 0.1) {
    tempPricescale = 1000000
  } else if (props.coinInfo?.amount < 100) {
    tempPricescale = 10000
  }
  return tempPricescale
})
/**
 * 临时交易(打开页面币种初始信息)
 */
const tempTrade = {
  time: '',
  amount: '',
  open: '',
  high: '',
  low: '',
  close: '',
  volume: '',
  lastClose: '',
  intervention: false
}
/**
 * 分辨率差
 */
const intervalDiff = ref('')
/**
 * 总分辨率列表
 */
const intervalList = getIntervalList()
/**
 * 指标列表
 */
const studyList = getStudyList()

const headIntervalList = reactive([])
const menuIntervalList = intervalList.filter((elem) => elem?.isMore)

/**
 * K线使用 分辨率列表
 */
let supportedResolutions = []
/**
 * 数据sdk实例
 */
let datafeeds = null
// 指标
let studies = reactive([])

/**
 * 当前symbol 切换时过渡
 */
let currentCoinInfo = reactive({})
/**
 * 当前interval 切换时过渡
 */
let currentInterval = reactive({})

/**
 * KLine
 */
const klineId = computed(() => `kline_${props.type}`)

let widget = null
const mainStore = useMainStore()
const tradeStore = useTradeStore()

/**
 * 交易对监听
 */
const eventTradeSymbolChange = debounce((e) => {
  // 监听币种切换
  let symbol = e.detail.symbol
  let tempCoinInfo = e.detail.coinInfo
  // 分辨率改变
  let tempHeadIntervalList = getHeadIntervalList(tempCoinInfo)

  if (
    tempHeadIntervalList.map((elem) => elem.value).join() !=
    headIntervalList.map((elem) => elem.value).join()
  ) {
    // 判断分辨率是否一致
    supportedResolutions = getSupportedResolutions()
    headIntervalList.splice(0, headIntervalList.length, ...tempHeadIntervalList)
    Object.assign(currentInterval, headIntervalList[0])
  }
  showMenu.value = false
  // 设置币种
  setSymbol(symbol, currentInterval.interval, () => {
    Object.assign(currentCoinInfo, tempCoinInfo)

    // 重新订阅实时数据
    subscribeTrades({
      coin: tempCoinInfo.coin,
      symbol: tempCoinInfo.coin,
      interval: currentInterval.key,
      firstDataRequest: false
    })
  })
}, 200)
/**
 * 获取分辨率
 */
const getSupportedResolutions = (tempCoinInfo = currentCoinInfo) => {
  let tempList = intervalList.map((elem) => elem.interval)
  if (tempCoinInfo?.market == 'mt5') {
    tempList = intervalList.filter((elem) => elem.market == 'mt5').map((elem) => elem.interval)
  }
  return tempList
}
/**
 * 获取分辨率显示菜单
 */
const getHeadIntervalList = (tempCoinInfo = currentCoinInfo) => {
  let tempList = intervalList.filter((elem) => !elem?.isMore)
  if (tempCoinInfo?.market == 'mt5' || tempCoinInfo?.coinType === 3) {
    tempList = intervalList.filter((elem) => elem.market == 'mt5')
  }
  return tempList
}
onMounted(async () => {
  Object.assign(currentCoinInfo, props.coinInfo)
  supportedResolutions = getSupportedResolutions()
  headIntervalList.splice(0, headIntervalList.length, ...getHeadIntervalList())
  Object.assign(currentInterval, headIntervalList[0])
  document.addEventListener('event_tradeSymbolChange', eventTradeSymbolChange)
  await loadTradingViewScript()
  nextTick(() => {
    initWidget()
  })
})

// loadTradingViewScript 函数已移至 utils/tradingview-loader.js

onBeforeUnmount(() => {
  document.removeEventListener('event_tradeSymbolChange', eventTradeSymbolChange)
  unsubscribeTrades(true)
  widget.remove()
})

/**
 * 设置币种、周期
 */
const setSymbol = async (symbol, interval, callBack) => {
  if (currentCoinInfo.symbol != symbol || interval != currentInterval.interval) {
    widget?.setSymbol(symbol, interval, () => {
      Object.assign(
        currentInterval,
        intervalList.find((elem) => elem.interval == interval)
      )
      callBack && callBack()
    })
  }
}

// 数据实例
const dataFeedInstance = {}
/**
 * 获取配置
 */
dataFeedInstance.getConfig = async (callback) => {
  setTimeout(() => {
    callback({
      // 分辨率
      supported_resolutions: supportedResolutions,
      supports_marks: false,
      supports_timescale_marks: true,
      supports_time: true
    })
  }, 0)
}
/**
 * 获取服务器时间
 */
dataFeedInstance.getServerTime = async (callback) => {
  let time = +new Date()
  callback && callback(time)
}
/**
 * 获取历史KLine数据
 */
dataFeedInstance.getBars = async ({ symbolInfo: coinInfo, resolution, from, firstDataRequest }) => {
  let tempInterval = intervalList.find((elem) => elem.interval == resolution)
  try {
    if (tempInterval && (from == '' || from > 0)) {
      let params = {
        symbol: coinInfo.coinUpperCase,
        interval: tempInterval.key,
        limit: 1000
      }
      if (from) {
        params.end = from
      }
      // let barList = await client.candles(params)
      const { data } = await getKlineHistory({
        ...params,
        interval: tempInterval.key,
        symbol: coinInfo.coinUpperCase,
        market: coinInfo.market
      })
      // console.log(data.ticker.symbol,55555555)
      /* tradeStore.setKlineTicker(data.ticker)
      let barList = data.historyKline */
      let barList = []
      if (data) {
        tradeStore.setKlineTicker(data.ticker)
        barList = data.historyKline
      }
      barList = barList
        .map((elem) => {
          // 兼容不同的数据格式：币使用完整字段名，其他币种使用缩写
          const open = elem.open !== undefined ? elem.open : elem.o;
          const high = elem.high !== undefined ? elem.high : elem.h;
          const low = elem.low !== undefined ? elem.low : elem.l;
          const close = elem.close !== undefined ? elem.close : elem.c;
          const volume = elem.volume !== undefined ? elem.volume : elem.v;
          const time = elem.timestamp !== undefined ? elem.timestamp : elem.T;

          // 数据验证和修正
          const openPrice = parseFloat(open) || 0;
          const highPrice = parseFloat(high) || 0;
          const lowPrice = parseFloat(low) || 0;
          const closePrice = parseFloat(priceFormat(close)) || 0;
          const volumeValue = parseFloat(volume) || 0;

          // 确保价格数据的合理性
          let validLow = lowPrice;
          let validHigh = highPrice;

          // 如果低价为0或异常，使用开盘价或收盘价的较小值
          if (validLow <= 0) {
            validLow = Math.min(openPrice, closePrice) || openPrice || closePrice || 1;
          }

          // 如果高价为0或小于低价，使用开盘价或收盘价的较大值
          if (validHigh <= 0 || validHigh < validLow) {
            validHigh = Math.max(openPrice, closePrice) || openPrice || closePrice || validLow || 1;
          }

          return {
            open: openPrice,
            high: validHigh,
            low: validLow,
            close: closePrice,
            amount: closePrice,
            volume: volumeValue,
            time: time
          }
        })
        .sort((a, b) => a.time - b.time)
      if (firstDataRequest) {
        let tempObj = barList.slice(-1)[0]

        tempTrade.amount = tempObj.amount
        tempTrade.open = tempObj.open
        tempTrade.close = tempObj.close
        tempTrade.high = tempObj.high
        tempTrade.low = tempObj.low
        tempTrade.volume = tempObj.volume
        tempTrade.time = tempObj.time
        tempTrade.lastClose = tempObj.close
        tempTrade.intervention = false

        intervalDiff.value = Math.abs(tempTrade.time - barList.slice(-2, -1)[0].time)
        updateDataKline(tempTrade)
        subscribeTrades({
          coin: coinInfo.coin,
          symbol: coinInfo.coin,
          interval: tempInterval.key,
          firstDataRequest: firstDataRequest
        })
        
        // 数据加载完成后初始化指标
        if (firstDataRequest && studyList.length > 0 && !currentStudy.value) {
          setTimeout(() => {
            setStudy(studyList[0].name)
          }, 2000)
        }
      }
      return barList
    }
  } catch (error) {
    unsubscribeTrades(true)
    return []
  }
  return []
}

/**
 * 加载商品配置
 */
dataFeedInstance.resolveSymbol = async () => {
  return {
    // 商品名称
    name: props.coinInfo.symbolUpperCase,
    // 自定义携带参数
    coin: props.coinInfo.coin,
    coinUpperCase: props.coinInfo.coin,
    symbol: props.coinInfo.symbol,
    symbolUpperCase: props.coinInfo.symbolUpperCase,
    market: props.coinInfo.market,
    // resolution: '1m',
    fractional: false,
    //设置周期
    session: '24x7',
    // 显示商品是否具有历史数据
    has_intraday: true,
    //设置是否支持周月线
    has_weekly_and_monthly: true,
    // 布尔值显示商品是否具有以日为单位的历史数据
    // has_daily: true,
    // 交易所名称
    exchange: __config._APP_EXCHANGE_NAME,
    //设置是否支持周月线
    description: props.coinInfo.symbolUpperCase,
    //设置价格精度  100表示保留两位小数   1000三位   10000四位
    pricescale:100,
    // 最小波动
    minmov: 1 / priceScale.value,
    // 分辨率数组
    supported_resolutions: supportedResolutions
  }
}

/**
 * 初始化图表
 */
const initWidget = () => {
  try {
    // 检查容器是否存在
    const container = document.getElementById(klineId.value)
    if (!container) {
      return
    }

    // 检查 TradingView 是否已加载
    if (typeof TradingView === 'undefined') {
      return
    }

    // 检查必要的属性
    if (!props.coinInfo?.symbolUpperCase) {
      return
    }

    datafeeds = new Datafees(dataFeedInstance)
    // 主题
    let theme = window.__theme

    // 使用工具函数获取正确的路径配置
    const pathConfig = getTradingViewPathConfig(theme)

    // 使用 Charting Library API 而不是 Widget API
    widget = new TradingView.widget({
		symbol: props.coinInfo.symbolUpperCase,
		theme,
		debug: false,
		autosize: true,
		// 默认分辨率
		interval: currentInterval.interval,
		container_id: klineId.value,
		datafeed: datafeeds,
		library_path: pathConfig.library_path,
		custom_css_url: pathConfig.custom_css_url,
		locale: 'en',

		timezone: mainStore.timezone,
		// 自定义日期格式化
		customFormatters: {
		  dateFormatter: {
			format(date) {
			  return _klineTimeFormat(date.getTime(), 'DD/MM/YYYY', true)
			}
		  },
		  timeFormatter: {
			format(date) {
			  return _klineTimeFormat(date.getTime(), 'HH:mm:ss', true)
			}
		  }
		},

		preset: 'mobile',
		onChartReady: () => {
		  // 尝试立即获取图表实例
		  const tryCreateStudy = () => {
		    if (studyList.length > 0 && studyList[0] && !currentStudy.value) {
		      setStudy(studyList[0].name)
		    }
		  }
		  
		  // 立即尝试一次
		  setTimeout(tryCreateStudy, 500)
		  
		  // 如果第一次失败，再延迟重试
		  setTimeout(tryCreateStudy, 2000)

		  // 确保实时数据订阅正常工作
		  if (currentCoinInfo.coin) {
		    subscribeTrades({
		      coin: currentCoinInfo.coin,
		      symbol: currentCoinInfo.coin,
		      interval: currentInterval.key,
		      firstDataRequest: false
		    })
		  }
		},
		onError: (error) => {
		  // 如果是 403 错误，显示用户友好的错误信息
		  if (error && error.toString().includes('403')) {
			const container = document.getElementById(klineId.value)
			if (container) {
			  container.innerHTML = `
				<div style="
				  display: flex;
				  flex-direction: column;
				  align-items: center;
				  justify-content: center;
				  height: 300px;
				  background: var(--ex-default-background-color);
				  border: 1px solid var(--ex-border-color1);
				  border-radius: 4px;
				  color: var(--ex-passive-font-color);
				  text-align: center;
				  padding: 20px;
				">
				  <div style="font-size: 16px; margin-bottom: 10px;">📊</div>
				  <div style="font-size: 14px; margin-bottom: 8px;">图表资源加载失败</div>
				  <div style="font-size: 12px; color: var(--ex-font-color1);">
					请检查网络连接或刷新页面重试
				  </div>
				</div>
			  `
			}
		  }
		},

		// 暂时移除 overrides 和 studies_overrides 来避免 403 错误
		...getConfig(theme)
	})

  } catch (error) {
    // 显示错误信息
    const container = document.getElementById(klineId.value)
    if (container) {
      container.innerHTML = `
        <div style="
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 300px;
          background: var(--ex-default-background-color);
          border: 1px solid var(--ex-border-color1);
          border-radius: 4px;
          color: var(--ex-passive-font-color);
          text-align: center;
          padding: 20px;
        ">
          <div style="font-size: 16px; margin-bottom: 10px;">📊</div>
          <div style="font-size: 14px; margin-bottom: 8px;">图表初始化失败</div>
          <div style="font-size: 12px; color: var(--ex-font-color1);">
            错误: ${error.message}
          </div>
        </div>
      `
    }
  }
}

/**
 * 创建指标
 */
const createStudy = () => {
  // 确保 widget 已初始化
  if (!widget) {
    return
  }

  // 使用 onChartReady 确保在正确的时机创建指标
  widget.onChartReady(() => {
    try {
      if (studyList && studyList.length > 0) {
        // 直接调用 setStudy，它内部已经使用了 onChartReady
        setStudy(studyList[0].name)
      }
    } catch (error) {
      // 静默处理错误
    }
  })
}
/**
 * 订阅客户端列表
 */
const subscribeClientList = []
/**
 * 取消订阅
 * @param {*} firstDataRequest
 */
const unsubscribeTrades = (firstDataRequest = false) => {
  if (currentCoinInfo.symbol) {
    _coinWebSocket.send({
      op: socketDict.unsubscribe,
      type: socketDict.KLINE,
      symbol: currentCoinInfo.symbol,
      interval: currentInterval.key
    })
    if (firstDataRequest) {
      subscribeClientList.forEach((subKey) => {
        subKey && PubSub.unsubscribe(subKey)
      })
      subscribeClientList.length = 0
      _coinWebSocket.send({
        op: socketDict.unsubscribe,
        type: socketDict.TRADE,
        symbol: currentCoinInfo.symbol
      })
    }
  }
}

/**
 * 订阅实时成交
 */
const subscribeTrades = async (params) => {
  // 先取消订阅
  unsubscribeTrades(params.firstDataRequest)

  _coinWebSocket.send({
    op: socketDict.subscribe,
    type: socketDict.KLINE,
    symbol: params.symbol,
    interval: params.interval
  })

  if (params.firstDataRequest) {
    _coinWebSocket.send({
      op: socketDict.subscribe,
      type: socketDict.TRADE,
      symbol: params.symbol
    })
  }
  let marketTradeKey = PubSub.subscribe(socketDict.TRADE, (key, data) => {
    // 实时成交
    if (data.symbol == params.symbol && data?.data?.tick?.data?.length > 0) {
      let tempData = data.data.tick.data[0]
      // console.log('实时成交', data.symbol, tempData)

      // 检查是否是当前K线的时间范围内
      if (
        tempTrade.time <= tempData.ts &&
        priceFormat(tempTrade.close) != priceFormat(tempData.price)
      ) {
        // 更新最高价
        if (tempTrade.high < tempData.price) {
          tempTrade.high = tempData.price
        }
        // 更新最低价
        if (tempTrade.low > tempData.price) {
          tempTrade.low = tempData.price
        }
        // 更新收盘价
        tempTrade.close = Number(priceFormat(tempData.price))

        // 使用节流函数更新数据，避免过于频繁的更新
        updateDataKlineThrottle(tempTrade)
      }
    }
  })
  subscribeClientList.push(marketTradeKey)
  let candlestickKey = PubSub.subscribe(socketDict.KLINE, (key, data) => {
    // K线数据
    // console.log('K线数据', data.symbol, data.data?.tick)
    let tempData = data.data?.tick

    if (data.symbol == params.symbol && tempData) {
      // 处理干预情况
      if (tempTrade.intervention != tempData?.intervention) {
        // console.log('干预', tempTrade.intervention, tempData?.intervention, tempTrade.lastClose)
        tempData.open = tempTrade.lastClose
        tempTrade.intervention = tempData?.intervention
      }

      // 计算本次时间 - 使用id作为时间戳，如果id不是时间戳则使用当前时间
      let tempTime = tempData.id || Date.now()
      // 对于分钟级别的K线，将时间对齐到分钟边界
      if (intervalDiff.value) {
        tempTime = parseInt(tempTime / intervalDiff.value) * intervalDiff.value
      }

      if (tempTrade.time < tempTime) {
        // console.log('新K线', tempData.open, tempTrade.time, tempTime, tempData)
        tempTrade.time = tempTime
        tempTrade.open = tempData.open
      }

      // 更新K线数据并进行数据验证
      const newHigh = parseFloat(tempData.high) || tempTrade.high || tempTrade.close || 1;
      const newLow = parseFloat(tempData.low) || tempTrade.low || tempTrade.close || 1;
      const newClose = Number(priceFormat(tempData.close)) || tempTrade.close || 1;
      const newVolume = parseFloat(tempData.vol) || 0;

      // 确保高低价的合理性
      tempTrade.high = Math.max(newHigh, newLow, newClose);
      tempTrade.low = Math.min(newLow > 0 ? newLow : newClose, newHigh, newClose);
      tempTrade.close = newClose;
      tempTrade.volume = newVolume;

      // 添加价格同步日志
      // console.log('K线价格更新', {
      //   symbol: data.symbol,
      //   原始数据: tempData,
      //   处理后: {
      //     open: tempTrade.open,
      //     high: tempTrade.high,
      //     low: tempTrade.low,
      //     close: tempTrade.close,
      //     volume: tempTrade.volume
      //   },
      //   数据来源: tempData.id ? '定时K线生成' : '实时交易更新',
      //   价格一致性检查: {
      //     收盘价: tempTrade.close,
      //     高价合理: tempTrade.high >= tempTrade.close,
      //     低价合理: tempTrade.low <= tempTrade.close && tempTrade.low > 0
      //   }
      // });

      // 更新图表数据
      updateDataKline(tempTrade)
    }
  })
  subscribeClientList.push(candlestickKey)
}
/**
 * 更新数据
 */
const updateDataKline = (newData) => {
  if (newData?.close) {
    // console.log('更新K线数据', newData)

    // 确保 datafeeds 存在
    if (datafeeds && typeof datafeeds.updateData === 'function') {
      // 确保数据格式正确，特别是收盘价
      const formattedData = {
        ...newData,
        close: Number(priceFormat(newData.close)), // 确保收盘价格式正确
        time: newData.time || Date.now()
      }

      // console.log('格式化后的K线数据:', formattedData)
      datafeeds.updateData(formattedData)

      // 强制刷新TradingView图表以确保价格标线更新
      if (widget && typeof widget.chart === 'function') {
        try {
          widget.chart().executeActionById('refresh')
        } catch (error) {
          // console.warn('刷新TradingView图表失败:', error)
        }
      }
    } else {
      // console.error('datafeeds 未初始化或 updateData 方法不存在')
    }

    // 发布数据更新事件
    PubSub.publish(socketDict.DETAIL, {
      data: {
        ...newData,
        vol: newData.volume
      },
      origin: 'kline',
      symbol: currentCoinInfo.coin,
      type: socketDict.DETAIL
    })
  } else {
    // console.warn('更新数据失败：缺少必要的数据', newData)
  }
}
/**
 * 更新数据 限流
 */
const updateDataKlineThrottle = throttle(function (newData) {
  updateDataKline(newData)
}, 300)
/**
 * 显示更多分辨率
 */
const showMenu = ref(false)
/**
 * 选中分辨率
 * @param {*}
 */
const checkedInterval = (item, type = '') => {
  if (item.interval != currentInterval.interval) {
    setSymbol(props.coinInfo.symbol, item.interval)
  }
  showMenu.value = !!type
}

// 指标选择
const currentStudy = ref('')
/**
 * 设置指标
 */
const setStudy = (name) => {
  if (currentStudy.value == name) {
    return
  }

  // 检查 widget 是否存在并且已初始化
  if (!widget) {
    return
  }

  try {
    // 获取图表实例的函数
    const getActiveChart = () => {
      let activeChart = null
      try {
        // 优先使用 widget.activeChart()
        if (typeof widget.activeChart === 'function') {
          activeChart = widget.activeChart()
        }
        
        // 如果失败，尝试使用 widget.chart()
        if (!activeChart && typeof widget.chart === 'function') {
          const chart = widget.chart()
          if (chart) {
            // chart 对象可能直接就是 activeChart，或者有 activeChart 方法
            if (typeof chart.activeChart === 'function') {
              activeChart = chart.activeChart()
            } else if (typeof chart.createStudy === 'function') {
              // chart 对象本身可能就是可用的
              activeChart = chart
            }
          }
        }
      } catch (error) {
        // 静默处理错误
      }
      return activeChart
    }
    
    let activeChart = getActiveChart()
    
    if (!activeChart || typeof activeChart.createStudy !== 'function') {
      // 如果直接获取失败，等待一段时间后重试
      let retryCount = 0
      const maxRetries = 3
      const retry = () => {
        activeChart = getActiveChart()
        if (activeChart && typeof activeChart.createStudy === 'function') {
          performStudyChange(activeChart, name)
        } else if (retryCount < maxRetries) {
          retryCount++
          setTimeout(retry, 800)
        }
      }
      setTimeout(retry, 800)
    } else {
      performStudyChange(activeChart, name)
    }

  } catch (error) {
    // 静默处理错误
  }
  
  // 执行指标切换的函数
  function performStudyChange(activeChart, name) {
    // 关闭旧指标
    if (currentStudy.value) {
      let oldStudy = studyList.find((elem) => elem.name == currentStudy.value)
      if (oldStudy && oldStudy.studyList && oldStudy.studyList.length > 0) {
        oldStudy.studyList.forEach((studyId) => {
          try {
            activeChart.removeEntity(studyId)
          } catch (error) {
            // 静默处理错误
          }
        })
        oldStudy.studyList = []
      }
    }

    // 设置新指标
    currentStudy.value = name
    let newStudy = studyList.find((elem) => elem.name == name)
    if (!newStudy) {
      return
    }

    // 初始化 studyList 数组
    if (!newStudy.studyList) {
      newStudy.studyList = []
    }

    // 创建新指标，使用 Promise.all 等待所有指标创建完成
    Promise.all(
      newStudy.cycleList.map(async (cycle, index) => {
        try {
          let result = ''
          if (name == 'MACD') {
            result = await activeChart.createStudy(newStudy.name, false, false, [], {})
          } else if (name == 'Bollinger Bands') {
            result = await activeChart.createStudy(newStudy.name, false, false, [], {})
          } else {
            result = await activeChart.createStudy(newStudy.name, false, false, [cycle], {
              'plot.color': newStudy.colorList[index],
              'plot.linewidth': 2
            })
          }
          if (result) {
            newStudy.studyList.push(result)
          }
          return result
        } catch (error) {
          return null
        }
      })
    ).catch(() => {
      // 静默处理错误
    })
  }
}
</script>
<template>
  <div>
    <div class="third">
      <div class="list">
        <div class="thirdLeft">
          <div
            :class="{
              'hightItem item ff-num': item.interval === currentInterval.interval,
              'item ff-num': true
            }"
            v-for="(item, index) in headIntervalList"
            :key="index"
            @click="checkedInterval(item)"
          >
            {{ item.value }}
          </div>
        </div>
        <!-- 更多 -->
        <!-- <div
          class="thirdRight"
          v-show="currentCoinInfo.market != 'mt5'"
          @click="showMenu = !showMenu"
        >

          <div>{{ _t18(`exchange_more`) }}</div>
          <svg-load v-if="!showMenu" name="jiantou-x" class="thirdRightImg"></svg-load>
          <svg-load v-if="showMenu" name="jiantou-s" class="thirdRightImg"></svg-load>
        </div> -->
      </div>
    </div>
    <div
      class="selectTimes"
      v-if="showMenu"
      @touchmove.prevent
      @mousewheel.prevent
      @click="showMenu = false"
    >
      <div class="times">
        <div
          v-for="(item, index) in menuIntervalList"
          :key="index"
          :class="{ hightItem: item.interval === currentInterval.interval, 'item ff-num': true }"
          @click="checkedInterval(item, 'menu')"
        >
          {{ item.value }}
        </div>
      </div>
    </div>
  </div>
  <div :id="klineId" class="candlestick"></div>
  <div class="studyList">
    <div
      :class="item.name === currentStudy ? 'hightItem studyItem' : 'studyItem'"
      v-for="(item, index) in studyList"
      :key="index"
      @click="setStudy(item.name)"
    >
      {{ item.label }}
    </div>
  </div>
</template>

<style lang="scss" scoped>
.candlestick {
  height: 348px;
  background-color: var(--ex-candlestick-bg);
}
.hightItem {
  color: var(--ex-font-color9) !important;
}
.third {
  margin-top: 10px;
  padding: 0px 15px 10px;
  border-bottom: 1px solid var(--ex-border-color);
  .list {
    background-color: #000;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .thirdLeft {
      flex: 1;
      background-color: var(--ex-default-background-color);
      display: flex;
      font-size: 14px;
      color: var(--ex-default-font-color);
      .item {
        flex: 1;
        margin-right: 30px;
        &:last-child {
          margin-right: 0;
        }
      }
    }
    .thirdRight {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: var(--ex-font-color9);
      .thirdRightImg {
        width: 10px;
        height: 6px;
        margin-left: 5px;
      }
    }
  }
}
.selectTimes {
  position: absolute;
  height: 100vh;
  width: var(--ex-max-width);
  background: rgba($color: #000000, $alpha: 0.6);
  z-index: 10;
  .times {
    background-color: var(--ex-default-background-color);
    position: absolute;
    width: 100%;
    height: 84px;
    display: flex;
    align-items: center;
    border-radius: 0px 0px 15px 15px;
    .item {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 15px;
      width: 37px;
      height: 23px;
      background: var(--ex-div-bgColor12);
      border-radius: 2px 2px 2px 2px;
      font-size: 12px;
      color: var(--ex-default-font-color);
    }
  }
}
.studyList {
  display: flex;
  padding: 10px 15px;
  .studyItem {
    font-size: 14px;
    color: var(--ex-default-font-color);
    margin-right: 30px;
  }
}
</style>
